/**
 * API服务模块
 * 提供与后端的统一接口调用
 */

import { service } from "./index";
import { API_ENDPOINTS } from "./config";
import type {
  LoginRequest,
  LoginResponse,
  RegisterRequest,
  User,
  Persona,
  ChatMessage,
  ChatResponse,
  Memory,
  UserPreference,
  PaginationParams,
  ApiResponse,
  PageResponse,
} from "@/types";

// ==================== 认证服务 ====================
export const authApi = {
  /**
   * 用户登录
   */
  login: (data: LoginRequest): Promise<LoginResponse> => {
    return service.post(API_ENDPOINTS.AUTH.LOGIN, data);
  },

  /**
   * 用户注册
   */
  register: (data: RegisterRequest): Promise<User> => {
    return service.post(API_ENDPOINTS.AUTH.REGISTER, data);
  },

  /**
   * 刷新令牌
   */
  refreshToken: (refreshToken: string): Promise<LoginResponse> => {
    return service.post(API_ENDPOINTS.AUTH.REFRESH, { refreshToken });
  },

  /**
   * 用户登出
   */
  logout: (): Promise<void> => {
    return service.post(API_ENDPOINTS.AUTH.LOGOUT);
  },

  /**
   * 获取用户信息
   */
  getProfile: (): Promise<User> => {
    return service.get(API_ENDPOINTS.AUTH.PROFILE);
  },

  /**
   * 修改密码
   */
  changePassword: (data: {
    oldPassword: string;
    newPassword: string;
  }): Promise<void> => {
    return service.post(API_ENDPOINTS.AUTH.CHANGE_PASSWORD, data);
  },
};

// ==================== 人格管理服务 ====================
export const personaApi = {
  /**
   * 获取人格列表
   */
  getPersonas: (params?: PaginationParams): Promise<PageResponse<Persona>> => {
    return service.get(API_ENDPOINTS.PERSONA.LIST, { params });
  },

  /**
   * 获取人格详情
   */
  getPersona: (id: string): Promise<Persona> => {
    return service.get(API_ENDPOINTS.PERSONA.DETAIL(id));
  },

  /**
   * 创建人格
   */
  createPersona: (data: Partial<Persona>): Promise<Persona> => {
    return service.post(API_ENDPOINTS.PERSONA.CREATE, data);
  },

  /**
   * 更新人格
   */
  updatePersona: (id: string, data: Partial<Persona>): Promise<Persona> => {
    return service.put(API_ENDPOINTS.PERSONA.UPDATE(id), data);
  },

  /**
   * 删除人格
   */
  deletePersona: (id: string): Promise<void> => {
    return service.delete(API_ENDPOINTS.PERSONA.DELETE(id));
  },

  /**
   * 切换人格
   */
  switchPersona: (
    personaId: string,
  ): Promise<{ success: boolean; message?: string }> => {
    return service.post(API_ENDPOINTS.PERSONA.SWITCH, { personaId });
  },

  /**
   * 获取当前人格
   */
  getCurrentPersona: (): Promise<Persona> => {
    return service.get(API_ENDPOINTS.PERSONA.CURRENT);
  },

  /**
   * 获取人格切换冷却信息
   */
  getCooldownInfo: (): Promise<{
    canSwitch: boolean;
    remainingTime?: number;
  }> => {
    return service.get(API_ENDPOINTS.PERSONA.COOLDOWN);
  },
};

// ==================== 聊天服务 ====================
export const chatApi = {
  /**
   * 发送消息
   */
  sendMessage: (data: {
    content: string;
    conversationId?: string;
    personaId?: string;
    attachments?: string[];
  }): Promise<ChatResponse> => {
    return service.post(API_ENDPOINTS.CHAT.SEND, data);
  },

  /**
   * 获取聊天历史
   */
  getChatHistory: (params: {
    conversationId?: string;
    page?: number;
    limit?: number;
  }): Promise<PageResponse<ChatMessage>> => {
    return service.get(API_ENDPOINTS.CHAT.HISTORY, { params });
  },

  /**
   * 获取会话列表
   */
  getConversations: (params?: PaginationParams): Promise<PageResponse<any>> => {
    return service.get(API_ENDPOINTS.CHAT.CONVERSATIONS, { params });
  },

  /**
   * 获取会话详情
   */
  getConversation: (id: string): Promise<any> => {
    return service.get(API_ENDPOINTS.CHAT.CONVERSATION(id));
  },

  /**
   * 删除会话
   */
  deleteConversation: (id: string): Promise<void> => {
    return service.delete(API_ENDPOINTS.CHAT.DELETE_CONVERSATION(id));
  },

  /**
   * 清空聊天历史
   */
  clearHistory: (): Promise<void> => {
    return service.post(API_ENDPOINTS.CHAT.CLEAR_HISTORY);
  },

  /**
   * 导出聊天记录
   */
  exportChat: (params: {
    conversationId?: string;
    format?: "json" | "txt" | "pdf";
  }): Promise<Blob> => {
    return service.get(API_ENDPOINTS.CHAT.EXPORT, {
      params,
      responseType: "blob",
    });
  },
};

// ==================== 记忆管理服务 ====================
export const memoryApi = {
  /**
   * 创建记忆
   */
  createMemory: (data: Partial<Memory>): Promise<Memory> => {
    return service.post(API_ENDPOINTS.MEMORY.CREATE, data);
  },

  /**
   * 获取用户记忆列表
   */
  getUserMemories: (
    userId: string,
    params?: {
      page?: number;
      size?: number;
      sortBy?: string;
      sortDir?: "asc" | "desc";
    },
  ): Promise<PageResponse<Memory>> => {
    return service.get(API_ENDPOINTS.MEMORY.LIST(userId), { params });
  },

  /**
   * 获取记忆详情
   */
  getMemory: (id: string): Promise<Memory> => {
    return service.get(API_ENDPOINTS.MEMORY.DETAIL(id));
  },

  /**
   * 更新记忆
   */
  updateMemory: (id: string, data: Partial<Memory>): Promise<Memory> => {
    return service.put(API_ENDPOINTS.MEMORY.UPDATE(id), data);
  },

  /**
   * 删除记忆
   */
  deleteMemory: (id: string): Promise<void> => {
    return service.delete(API_ENDPOINTS.MEMORY.DELETE(id));
  },

  /**
   * 搜索相似记忆
   */
  searchSimilarMemories: (
    userId: string,
    params: {
      query: string;
      limit?: number;
    },
  ): Promise<Memory[]> => {
    return service.get(API_ENDPOINTS.MEMORY.SEARCH(userId), { params });
  },

  /**
   * 获取记忆统计
   */
  getMemoryStatistics: (userId: string): Promise<Record<string, any>> => {
    return service.get(API_ENDPOINTS.MEMORY.STATISTICS(userId));
  },

  /**
   * 聚类用户记忆
   */
  clusterUserMemories: (
    userId: string,
    params: {
      maxClusters?: number;
    },
  ): Promise<any[]> => {
    return service.get(API_ENDPOINTS.MEMORY.CLUSTERS(userId), { params });
  },

  /**
   * 批量删除记忆
   */
  batchDeleteMemories: (
    userId: string,
    memoryIds: string[],
  ): Promise<Record<string, any>> => {
    return service.delete(API_ENDPOINTS.MEMORY.BATCH_DELETE(userId), {
      data: memoryIds,
    });
  },
};

// ==================== 用户偏好服务 ====================
export const preferencesApi = {
  /**
   * 获取用户偏好
   */
  getUserPreferences: (): Promise<UserPreference> => {
    return service.get(API_ENDPOINTS.PREFERENCES.GET);
  },

  /**
   * 更新用户偏好
   */
  updateUserPreferences: (
    data: Partial<UserPreference>,
  ): Promise<UserPreference> => {
    return service.put(API_ENDPOINTS.PREFERENCES.UPDATE, data);
  },

  /**
   * 更新语言偏好
   */
  updateLanguagePreference: (language: string): Promise<void> => {
    return service.put(API_ENDPOINTS.PREFERENCES.LANGUAGE, { language });
  },

  /**
   * 更新人格偏好
   */
  updatePersonalityPreference: (
    personality: Record<string, any>,
  ): Promise<void> => {
    return service.put(API_ENDPOINTS.PREFERENCES.PERSONALITY, { personality });
  },

  /**
   * 更新通知偏好
   */
  updateNotificationPreference: (
    notifications: Record<string, any>,
  ): Promise<void> => {
    return service.put(API_ENDPOINTS.PREFERENCES.NOTIFICATIONS, {
      notifications,
    });
  },

  /**
   * 更新隐私偏好
   */
  updatePrivacyPreference: (privacy: Record<string, any>): Promise<void> => {
    return service.put(API_ENDPOINTS.PREFERENCES.PRIVACY, { privacy });
  },

  /**
   * 重置用户偏好
   */
  resetUserPreferences: (): Promise<UserPreference> => {
    return service.post(API_ENDPOINTS.PREFERENCES.RESET);
  },

  /**
   * 导出用户偏好
   */
  exportUserPreferences: (): Promise<Blob> => {
    return service.get(API_ENDPOINTS.PREFERENCES.EXPORT, {
      responseType: "blob",
    });
  },

  /**
   * 删除用户偏好
   */
  deleteUserPreferences: (): Promise<void> => {
    return service.delete(API_ENDPOINTS.PREFERENCES.DELETE);
  },
};

// ==================== 多模态处理服务 ====================
export const multimodalApi = {
  /**
   * 上传文件
   */
  uploadFile: (
    file: File,
    options?: {
      onProgress?: (progress: number) => void;
    },
  ): Promise<{ id: string; url: string; metadata?: any }> => {
    const formData = new FormData();
    formData.append("file", file);

    return service.post(API_ENDPOINTS.MULTIMODAL.UPLOAD, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
      onUploadProgress: (progressEvent) => {
        if (options?.onProgress && progressEvent.total) {
          const progress = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total,
          );
          options.onProgress(progress);
        }
      },
    });
  },

  /**
   * 处理图像
   */
  processImage: (data: {
    imageUrl?: string;
    imageFile?: File;
    task: "analyze" | "caption" | "ocr" | "enhance";
    options?: Record<string, any>;
  }): Promise<any> => {
    return service.post(API_ENDPOINTS.MULTIMODAL.PROCESS_IMAGE, data);
  },

  /**
   * 处理音频
   */
  processAudio: (data: {
    audioUrl?: string;
    audioFile?: File;
    task: "transcribe" | "analyze" | "enhance";
    options?: Record<string, any>;
  }): Promise<any> => {
    return service.post(API_ENDPOINTS.MULTIMODAL.PROCESS_AUDIO, data);
  },

  /**
   * 生成图像
   */
  generateImage: (data: {
    prompt: string;
    style?: string;
    size?: string;
    quality?: string;
  }): Promise<{ imageUrl: string; metadata?: any }> => {
    return service.post(API_ENDPOINTS.MULTIMODAL.GENERATE_IMAGE, data);
  },

  /**
   * 文本转语音
   */
  textToSpeech: (data: {
    text: string;
    voice?: string;
    speed?: number;
    pitch?: number;
  }): Promise<{ audioUrl: string; duration?: number }> => {
    return service.post(API_ENDPOINTS.MULTIMODAL.TEXT_TO_SPEECH, data);
  },

  /**
   * 语音转文本
   */
  speechToText: (data: {
    audioUrl?: string;
    audioFile?: File;
    language?: string;
  }): Promise<{ text: string; confidence?: number }> => {
    return service.post(API_ENDPOINTS.MULTIMODAL.SPEECH_TO_TEXT, data);
  },
};

// ==================== 文件管理服务 ====================
export const filesApi = {
  /**
   * 上传文件
   */
  uploadFile: (
    file: File,
    options?: {
      onProgress?: (progress: number) => void;
    },
  ): Promise<any> => {
    const formData = new FormData();
    formData.append("file", file);

    return service.post(API_ENDPOINTS.FILES.UPLOAD, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
      onUploadProgress: (progressEvent) => {
        if (options?.onProgress && progressEvent.total) {
          const progress = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total,
          );
          options.onProgress(progress);
        }
      },
    });
  },

  /**
   * 下载文件
   */
  downloadFile: (id: string): Promise<Blob> => {
    return service.get(API_ENDPOINTS.FILES.DOWNLOAD(id), {
      responseType: "blob",
    });
  },

  /**
   * 删除文件
   */
  deleteFile: (id: string): Promise<void> => {
    return service.delete(API_ENDPOINTS.FILES.DELETE(id));
  },

  /**
   * 获取文件列表
   */
  getFiles: (params?: PaginationParams): Promise<PageResponse<any>> => {
    return service.get(API_ENDPOINTS.FILES.LIST, { params });
  },

  /**
   * 获取文件元数据
   */
  getFileMetadata: (id: string): Promise<any> => {
    return service.get(API_ENDPOINTS.FILES.METADATA(id));
  },
};

// ==================== 伦理控制服务 ====================
export const ethicsApi = {
  /**
   * 过滤用户输入
   */
  filterUserInput: (
    content: string,
  ): Promise<{
    filtered: boolean;
    filteredContent?: string;
    reasons?: string[];
  }> => {
    return service.post(API_ENDPOINTS.ETHICS.FILTER_INPUT, { content });
  },

  /**
   * 过滤AI输出
   */
  filterAIOutput: (
    content: string,
  ): Promise<{
    filtered: boolean;
    filteredContent?: string;
    reasons?: string[];
  }> => {
    return service.post(API_ENDPOINTS.ETHICS.FILTER_OUTPUT, { content });
  },

  /**
   * 检查人格切换权限
   */
  checkPersonaSwitch: (
    personaId: string,
  ): Promise<{
    canSwitch: boolean;
    reason?: string;
    remainingTime?: number;
  }> => {
    return service.post(API_ENDPOINTS.ETHICS.CHECK_SWITCH, { personaId });
  },

  /**
   * 获取人格切换统计
   */
  getPersonaSwitchStats: (): Promise<Record<string, any>> => {
    return service.get(API_ENDPOINTS.ETHICS.SWITCH_STATS);
  },

  /**
   * 获取人格切换历史
   */
  getPersonaSwitchHistory: (
    params?: PaginationParams,
  ): Promise<PageResponse<any>> => {
    return service.get(API_ENDPOINTS.ETHICS.SWITCH_HISTORY, { params });
  },
};

// ==================== 系统服务 ====================
export const systemApi = {
  /**
   * 健康检查
   */
  healthCheck: (): Promise<{
    status: "healthy" | "degraded" | "unhealthy";
    timestamp: string;
    version: string;
  }> => {
    return service.get(API_ENDPOINTS.SYSTEM.HEALTH);
  },

  /**
   * 获取系统状态
   */
  getSystemStatus: (): Promise<Record<string, any>> => {
    return service.get(API_ENDPOINTS.SYSTEM.STATUS);
  },

  /**
   * 获取系统指标
   */
  getSystemMetrics: (): Promise<Record<string, any>> => {
    return service.get(API_ENDPOINTS.SYSTEM.METRICS);
  },
};

// 导出所有API服务
export default {
  auth: authApi,
  persona: personaApi,
  chat: chatApi,
  memory: memoryApi,
  preferences: preferencesApi,
  multimodal: multimodalApi,
  files: filesApi,
  ethics: ethicsApi,
  system: systemApi,
};
